package com.ljz.servlet;

import com.ljz.entity.User;
import com.ljz.service.UserService;
import com.ljz.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    UserService userService = new UserServiceImpl();

    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
//        req.setCharacterEncoding("utf-8");
//        resp.setContentType("text/html;charset=utf-8");
        User user = new User();
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        double time = Double.parseDouble(req.getParameter("time"));
        user.setUname(username);
        user.setPassword(password);
        boolean result = userService.findByUname(user);
        PrintWriter out = resp.getWriter();
        if (result){
            req.getSession().setAttribute("user", user);
            String encodedUsername = URLEncoder.encode(username, "UTF-8");
            Cookie cookie = new Cookie("name",encodedUsername);
            cookie.setMaxAge((int) (60*60*24*time));
            resp.addCookie(cookie);
            out.print("<script> alert('登陆成功')</script>");
            out.print("<script> location.href='index.html'</script>");
        }else {
            resp.sendRedirect("login.html");
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
